package cn.edu.zime.tjh.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class EchoUDPClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
        // 接收回显
        ByteBuf content = packet.content();
        String response = content.toString(CharsetUtil.UTF_8);

        InetSocketAddress sender = packet.sender();
        System.out.printf("Client received [%s:%d]: %s%n",
                sender.getAddress().getHostAddress(),
                sender.getPort(),
                response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
